package cn.nawang.ebeim.ui.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cn.nawang.ebeim.client.util.PropertiesConstants;
import cn.nawang.ebeim.client.util.PropertiesUtil;
import cn.nawang.ebeim.ui.bean.Constant;
import cn.nawang.ebeim.ui.bean.User;
import cn.nawang.ebeim.ui.util.ApiUtil;
import cn.nawang.ebeim.ui.util.DatasourceSecurityRankUtil;
import cn.nawang.ebeim.ui.util.MACAddress;

/**
 * @ClassName: LoginController
 * @Description: TODO
 * @author fanyb
 * @date Nov 12, 2015 5:43:20 PM
 * @version v1.0
 */
@RestController
public class LoginController {
  private static final Logger LOG = LoggerFactory.getLogger(LoginController.class);
  
  @Autowired
  private HttpSession session;
  
  /**
   * @author zhangjf
   * @Description: 登入
   * @param @param user
   * @param @param request
   * @param @return
   * @param @throws Exception
   * @return String
   * @date 2015年10月29日上午8:52:21
   *
   * @修改人 zhangjf
   * @修改日期
   */
  @RequestMapping(value = "login", method = RequestMethod.POST)
  public String login(@RequestBody User user, HttpServletRequest request) throws Exception {
    LOG.info("login: - user: {}", user);
    user.setCode("web_ui_login_code_200");
    String rs = ApiUtil.login(user);
    JSONObject json = null;
    try {
      json = JSONObject.parseObject(rs);
    } catch (Exception e) {
      json = new JSONObject();
      json.put("code", "404");
      json.put("message", "api请求失败！");
      return json.toString();
    }
    JSONObject userJson = json.getJSONObject("user");
    if (userJson != null) {
      User rsUser = JSONObject.toJavaObject(userJson, User.class);
      if (((Integer) json.get("code")) == 200) {
        // 都不是第一次登录且默认密码也修改过才会放到session中
        if (!Constant.USER_IS_FIRST_LOGIN_YES.equals(rsUser.getIsUpdateDefaultPwd())
            && !Constant.USER_IS_FIRST_LOGIN_YES.equals(rsUser.getIsFirstLogin())) {
          request.getSession().setAttribute("user", rsUser);
        }
        String localBindDevice = MACAddress.getMACAddr();
        // 有绑定并且绑定的设备不是本机，去除登录状态
        if (rsUser.getBindDevice() != null && !localBindDevice.equals(rsUser.getBindDevice())) {
          request.getSession().removeAttribute("user");
        }
        // 授权过期也不能登陆到系统
        if ("authOver".equals(json.get("overAutuTimestatus"))) {
          request.getSession().removeAttribute("user");
        }
        rsUser.setPassword(user.getPassword());
        PropertiesUtil.writeProperties(PropertiesConstants.CUSTOMER_ID, rsUser.getCustomerId());
        PropertiesUtil.writeProperties(PropertiesConstants.USER_ID, rsUser.getId());
      }
    }

    return rs;
  }
  
  /**
   * @author zhangjf
   * @Description: 退出
   * @param @return
   * @return String
   * @date 2015年10月29日上午8:52:33
   *
   * @修改人 zhangjf
   * @修改日期
   */
  @RequestMapping(value = "logout", method = RequestMethod.GET)
  public String logout() {
    JSONObject json = new JSONObject();
    json.put("code", "200");
    session.removeAttribute("user");
    session.removeAttribute(DatasourceSecurityRankUtil.SESSION_CODE);
    return json.toString();
  }
  
  /**
   * 
   * @author fanyb
   * @Description: 用户名查找用户对象
   * @param username
   * @return String
   * @date Nov 5, 20159:52:04 AM
   *
   * @修改人
   * @修改日期
   */
  @RequestMapping(value = "/noIntercept/user/username", method = RequestMethod.GET)
  public String getBackupLog(String username) {
    LOG.info("/user/username - {}", username);
    String result = ApiUtil.findByUsername(username);
    return result;
  }

  /**
   * @author zhangjf
   * @Description: 获取用户信息
   * @param @return
   * @return String
   * @date 2015年10月29日上午8:53:21
   *
   * @修改人 zhangjf
   * @修改日期
   */
  @RequestMapping(value = "userinfo", method = RequestMethod.GET)
  public String getUserinfo() {
    User user = (User) session.getAttribute("user");
    String rs = ApiUtil.login(user);
    return rs;
  }
}
